//
//  ChatViewController.m
//  79环信
//
//  Created by 刘恒槟 on 15/8/2.
//  Copyright (c) 2015年 刘恒槟. All rights reserved.
//

#import "ChatViewController.h"
#import "ToolView.h"
#import "EMVoiceConverter.h"
#import <MediaPlayer/MediaPlayer.h>
#import <AVFoundation/AVFoundation.h>
#import <MobileCoreServices/MobileCoreServices.h>
#import "UITableViewCell+Func.h"
#import "BigImageViewViewController.h"
#import "EaseMob.h"
#import "SeedManager.h"


#import <CoreMedia/CoreMedia.h>


@interface ChatViewController ()<UITableViewDelegate,UITableViewDataSource,EMChatManagerDelegate,UIImagePickerControllerDelegate,UIActionSheetDelegate,UINavigationControllerDelegate>

@property (strong, nonatomic) IBOutlet UITableView *tableView;
@property (strong, nonatomic) IBOutlet UIView *toolV;


@property (strong, nonatomic) ToolView *toolView;
@property (strong, nonatomic) NSMutableArray *message_arr;

@property (nonatomic,strong)UIImage *ImaGe;

@property (strong,nonatomic)UIImagePickerController * imagePicker;

@property(nonatomic,strong)SeedManager *seedM;
@end

@implementation ChatViewController

- (void)viewDidLoad {
    [super viewDidLoad];
 
    //cell高度rowHeight 自适应的高度
    self.tableView.estimatedRowHeight = 80;
    //2.开启自动行高
    self.tableView.rowHeight = UITableViewAutomaticDimension;

    
    
    self.seedM = [[SeedManager alloc]init];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:
     UIKeyboardWillChangeFrameNotification  object:nil];
    // Do any additional setup after loading the view.
    self.imagePicker = [[UIImagePickerController alloc]init];
    self.navigationItem.title = self.charDic[@"groupName"];

    self.ImaGe = [[UIImage alloc]init];

    
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.imagePicker.delegate = self;
//    [UIScreen mainScreen].bounds
    
    self.toolView = [[ToolView alloc]initWithFrame:[UIScreen mainScreen].bounds];

//    self.toolView = [[ToolView alloc]initWithFrame:self.toolV.bounds];
    
    [self.toolV addSubview:self.toolView];
    
    self.toolView.backgroundColor = [UIColor clearColor];
    
    self.tableView.tableFooterView = [[UIView alloc]init];
    
    [self setUpToolViewBlockHuandle];
  

    
    NSArray * arr = [self.conversation loadAllMessages];
    self.message_arr = [NSMutableArray array];
    self.message_arr = [self messageWithArray:arr];
    [self.tableView reloadData];
    [self setTableViewScoll];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveNoti:) name:UIKeyboardWillChangeFrameNotification
                 object:nil];
    
    
}

-(NSMutableArray *)messageWithArray:(NSArray *)arr
{
    
    NSMutableArray * messageArr = [NSMutableArray array];
    
    for (int i = 0; i<arr.count; i++)
    {
        
        EMMessage * message = arr[i];
        
        
        if ([message.to isEqualToString:self.conversation.chatter]) {
            
            
            //拿到我发送的消息
            id<IEMMessageBody>msgbody = message.messageBodies.firstObject;
            if (msgbody.messageBodyType == eMessageBodyType_Text) {
                NSString * str = ((EMTextMessageBody *)msgbody).text;
                
                NSDictionary * dic =
                @{@"cellType":@"MyTextCell",@"msg":str};
                
                [messageArr addObject:dic];
               
            }
            else if(msgbody.messageBodyType == eMessageBodyType_Image)
            {
                
                
                UIImage *image = [UIImage imageWithContentsOfFile:((EMImageMessageBody *)msgbody).thumbnailLocalPath];

                NSDictionary *dic = @{@"cellType":@"MyImageCell",@"msg":image};
      
                [messageArr addObject:dic];

               
                

            }
            else if (msgbody.messageBodyType == eMessageBodyType_Voice)
            {
                //用一个EMVoiceMessageBody类型的对象来接收消息数组里的第一个元素
                EMVoiceMessageBody * body = ((EMVoiceMessageBody *)msgbody).message.messageBodies.firstObject;
                
                //判断是否下载完成
                if (body.attachmentDownloadStatus == EMAttachmentDownloadSuccessed) {
                    
                    //调用处理语音消息的方法
                    NSURL * voiceUrl = [self playReceiveVoiceWithBody:body];
                 
                    NSDictionary * dic = @{@"cellType":@"MyVoiceCell",@"msg":voiceUrl};

                    [messageArr addObject:dic];
           
                    
                }else{
                    
                    //若语音消息没有下载完成，则调用SDK中提供的下载方法下载
                    [[EaseMob sharedInstance].chatManager asyncFetchMessage:body.message progress:nil completion:^(EMMessage *aMessage, EMError *error) {
                        //下载完成后的回调
                        //判断是否下载成功
                        if (!error) {
                            //防御编程   判断语音是否下载成功
                            if (body.attachmentDownloadStatus == EMAttachmentDownloadSuccessed) {
                                
                                //用一个EMVoiceMessageBody类型的对象来接收消息数组里的第一个元素
                                EMVoiceMessageBody * messageBody=(EMVoiceMessageBody *)message.messageBodies.firstObject;
                                
                                //调用处理语音消息的方法
                                NSURL * voiceUrl = [self playReceiveVoiceWithBody:messageBody];
                                NSDictionary * dic = @{@"cellType":@"OtherVoiceCell",@"msg":voiceUrl};
                                
                                [messageArr addObject:dic];
                                

                            }
                        }
                    } onQueue:nil];
                }
            }

        }else{
            //对方发送的消息
            id<IEMMessageBody>msgbody = message.messageBodies.firstObject;
            
            if (msgbody.messageBodyType == eMessageBodyType_Text) {
                
                NSString * str = ((EMTextMessageBody *)msgbody).text;
              
                NSDictionary * dic =
                @{@"cellType":@"OtherTextCell",@"msg":str};
                
                [messageArr addObject:dic];
                
            }
            else if (msgbody.messageBodyType == eMessageBodyType_Image)
            {
                UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:((EMImageMessageBody *)msgbody).thumbnailRemotePath]]];
              
//                [self setValue:image forKey:@"otherImageCell"];
                NSDictionary *dic = @{@"cellType":@"OtherImageCell",@"msg":image};
                [messageArr addObject:dic];

            }
            else if (msgbody.messageBodyType == eMessageBodyType_Voice){
                
                
                
                //用一个EMVoiceMessageBody类型的对象来接收消息数组里的第一个元素
                EMVoiceMessageBody * body = ((EMVoiceMessageBody *)msgbody).message.messageBodies.firstObject;
                
                //判断是否下载完成
                if (body.attachmentDownloadStatus == EMAttachmentDownloadSuccessed) {
                    
                    //调用处理语音消息的方法
                    NSURL * voiceUrl = [self playReceiveVoiceWithBody:body];
                    
                  
                    
                    NSDictionary * dic = @{@"cellType":@"OtherVoiceCell",@"msg":voiceUrl};
                    
                    [messageArr addObject:dic];
                    
                }else{
                    
                    //若语音消息没有下载完成，则调用SDK中提供的下载方法下载
                    [[EaseMob sharedInstance].chatManager asyncFetchMessage:body.message progress:nil completion:^(EMMessage *aMessage, EMError *error) {
                        //下载完成后的回调
                        //判断是否下载成功
                        if (!error) {
                            //防御编程   判断语音是否下载成功
                            if (body.attachmentDownloadStatus == EMAttachmentDownloadSuccessed)
                            {
                                
                                //用一个EMVoiceMessageBody类型的对象来接收消息数组里的第一个元素
                                EMVoiceMessageBody * messageBody=(EMVoiceMessageBody *)message.messageBodies.firstObject;
                                
                                //调用处理语音消息的方法
                                NSURL * voiceUrl = [self playReceiveVoiceWithBody:messageBody];
                             
                                
                                NSDictionary * dic = @{@"cellType":@"OtherVoiceCell",@"msg":voiceUrl};
                                
                                [messageArr addObject:dic];

                            }
                        }
                    } onQueue:nil];
                }
            }

        }
     
         
    }
    
    return messageArr;
}

-(void)viewWillAppear:(BOOL)animated{
    
    [super viewWillAppear:animated];
    
    [self addDelegate];
    
}
-(void)viewDidAppear:(BOOL)animated
{
    
    [super viewDidAppear:animated];
    [self.tableView reloadData];
    [self setTableViewScoll];
    
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"ChatViewConTrollerWillDisMiss" object:nil];
    
    [self removeDelegate];
    
}
-(void)addDelegate
{
    
    [self removeDelegate];
    
    [[EaseMob sharedInstance].chatManager addDelegate:self delegateQueue:nil];
    
}
-(void)removeDelegate
{
    
    [[EaseMob sharedInstance].chatManager removeDelegate:self];
    
}

-(void)didReceiveMessage:(EMMessage *)message
{

    id<IEMMessageBody>msgbody = message.messageBodies.firstObject;
    
    if (msgbody.messageBodyType == eMessageBodyType_Text)
    {
        NSString * str = ((EMTextMessageBody *)msgbody).text;
       
        NSDictionary * dic =
        @{@"cellType":@"OtherTextCell",@"msg":str};

        [self.message_arr addObject:dic];
        [self.tableView reloadData];
        [self setTableViewScoll];
        
    }
    else if (msgbody.messageBodyType == eMessageBodyType_Image)
    {
        UIImage *image = [UIImage imageWithContentsOfFile:((EMImageMessageBody *)msgbody).thumbnailLocalPath];
        
        NSDictionary *dic = @{@"cellType":@"MyImageCell",@"msg":image};
        
        [self.message_arr addObject:dic];
        [self.tableView reloadData];
        [self setTableViewScoll];
    }
    else if (msgbody.messageBodyType == eMessageBodyType_Voice)
    {
        
        //用一个EMVoiceMessageBody类型的对象来接收消息数组里的第一个元素
        EMVoiceMessageBody * body = ((EMVoiceMessageBody *)msgbody).message.messageBodies.firstObject;
        
        //判断是否下载完成
        if (body.attachmentDownloadStatus == EMAttachmentDownloadSuccessed)
        {
            
            //调用处理语音消息的方法
            NSURL * voiceUrl = [self playReceiveVoiceWithBody:body];
            

            
            NSDictionary * dic = @{@"cellType":@"OtherVoiceCell",@"msg":voiceUrl};
            
            [self.message_arr addObject:dic];
            [self.tableView reloadData];
            [self setTableViewScoll];
            
        }
        else
        {
            
            //若语音消息没有下载完成，则调用SDK中提供的下载方法下载
            [[EaseMob sharedInstance].chatManager asyncFetchMessage:body.message progress:nil completion:^(EMMessage *aMessage, EMError *error) {
                //下载完成后的回调
                //判断是否下载成功
                if (!error) {
                    //防御编程   判断语音是否下载成功
                    if (body.attachmentDownloadStatus == EMAttachmentDownloadSuccessed) {
                        
                        //用一个EMVoiceMessageBody类型的对象来接收消息数组里的第一个元素
                        EMVoiceMessageBody * messageBody=(EMVoiceMessageBody *)message.messageBodies.firstObject;
                        
                        //调用处理语音消息的方法
                        NSURL * voiceUrl = [self playReceiveVoiceWithBody:messageBody];
                        
                    
                        
                        NSDictionary * dic = @{@"cellType":@"OtherVoiceCell",@"msg":voiceUrl};
                        
                        [self.message_arr addObject:dic];
                        [self.tableView reloadData];
                        [self setTableViewScoll];
                    }
                }
            } onQueue:nil];
        }
    }
}

#pragma - mark 处理接收到的语音消息
-(NSURL *)playReceiveVoiceWithBody:(EMVoiceMessageBody *)body{
    
    //先截取出语音消息的路径
    NSString * str=[body.localPath substringToIndex:body.localPath.length-3];
    //将语音消息路径后缀拼接为wav
    NSString * wavUrl= [NSString stringWithFormat:@"%@wav",str];
    
    //调用转码方法将收到的AMR格式的语音转为WAV格式
    BOOL  zhuanhuan=[self convertAMR:body.localPath toWAV:wavUrl];
    //判断是否转码成功
    if (!zhuanhuan) {
    //如果失败，返回空
        return nil;
    }
    //语音URL储存转换后的WAV格式语音的路径
    NSURL * voiceUrl=[NSURL fileURLWithPath:wavUrl];
    return voiceUrl;

}

-(void)setUpToolViewBlockHuandle
{
    
    __weak __block ChatViewController * copy_self = self;
    self.toolView.sendBlockHandle = ^(NSString * str)
    {

        if ([str isEqualToString:nil])
        {
            return ;
        }
        else
        {
        EMChatText * text = [[EMChatText alloc]initWithText:str];
        EMTextMessageBody * body = [[EMTextMessageBody alloc]initWithChatObject:text];
        EMMessage * message = [[EMMessage alloc]initWithReceiver:copy_self.conversation.chatter bodies:@[body]];

          message.messageType = eConversationTypeGroupChat;
            
        NSUserDefaults *user1 = [NSUserDefaults standardUserDefaults];
        NSString *usertoken = [user1 objectForKey:@"usertoken"];
        
        
        NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
        NSString *groupid = [user objectForKey:@"GROUPID"];
        
//            NSString *message1 = [NSString stringWithFormat:@"%@",message];
            
            [copy_self.seedM seedNewsWithToken:usertoken andMessage:str andGroupId:groupid BlockHandle:^(NSDictionary *dic) {
            
            NSString *str1 = [NSString stringWithFormat:@"%@",dic[@"status"]];
            if ([str1 isEqualToString:@"0"])
            {
                NSDictionary * dic = @{@"cellType":@"MyTextCell",@"msg":str};
                [copy_self.message_arr addObject:dic];
                
                [copy_self.tableView reloadData];
                [copy_self setTableViewScoll];
            }
            else
            {
                
            }
        }];
        }
        
        
//        EMChatText * text = [[EMChatText alloc]initWithText:str];
//        EMTextMessageBody * body = [[EMTextMessageBody alloc]initWithChatObject:text];
//        EMMessage * message = [[EMMessage alloc]initWithReceiver:copy_self.conversation.chatter bodies:@[body]];
//          message.messageType = eConversationTypeGroupChat;
//        //message.messageType = self.conversation.conversationType;
//        
//        [[EaseMob sharedInstance].chatManager asyncSendMessage:message progress:nil prepare:^(EMMessage *message, EMError *error)
//        {
//  
//    
//            NSDictionary * dic = @{@"cellType":@"MyTextCell",@"msg":str};
//            [copy_self.message_arr addObject:dic];
//            [copy_self.tableView reloadData];
//            [copy_self setTableViewScoll];
//        } onQueue:nil completion:nil onQueue:nil];
//
    };
    
    [self.toolView setSendVoiceBlockHandle:^(NSURL * url)
    {
       
        EMChatVoice * voice = [[EMChatVoice alloc]initWithFile:url.path displayName:@"displayName.wav"];
        
        EMVoiceMessageBody * voiceBody = [[EMVoiceMessageBody alloc]initWithChatObject:voice];
        EMMessage * message = [[EMMessage alloc]initWithReceiver:copy_self.conversation.chatter bodies:@[voiceBody]];
          message.messageType = eConversationTypeGroupChat;
        
        [[EaseMob sharedInstance].chatManager asyncSendMessage:message progress:nil prepare:^(EMMessage *message, EMError *error) {
          
            NSDictionary * dic = @{@"cellType":@"MyVoiceCell",@"msg":url};
            [copy_self.message_arr addObject:dic];

            [copy_self.tableView reloadData];
            [copy_self setTableViewScoll];

        } onQueue:nil completion:nil onQueue:nil];
    }];
    
    self.toolView.tapFunction = ^(Function fun)
    {
        
        if (fun == FunctionVoiceCall) {
            
            NSLog(@"进行语音通话");
            
            [copy_self voiceCall];
            
        }else if (fun == FunctionVideoCall){
            
            NSLog(@"进行视频通话");
            
            [copy_self videoCall];
        }
        if (fun == FunctionPhoto)
        {
            
            NSLog(@"发送图片");
            
            
            
            [copy_self seedPhoto];
            
        }
        
    };
    
    

}

-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    switch (buttonIndex)
    {
        case 1:{
            
            // 来自相册
           
                self.imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
                [self presentViewController:self.imagePicker animated:YES completion:nil];
        }
            break;
        case 0:
        {
            // 来自相机
            if (![UIImagePickerController availableMediaTypesForSourceType: UIImagePickerControllerSourceTypeCamera])
            {
            
                return;
            }
            // 开启相机
            self.imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
            self.imagePicker.mediaTypes = [[NSArray alloc]initWithObjects:(NSString *)kUTTypeMovie, nil];
            [self presentViewController:self.imagePicker animated:YES completion:nil];
        }
            break;
            
        default:
            break;
    }
}


-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
        UIImage *image = info[UIImagePickerControllerOriginalImage];
    
    self.ImaGe = image;
    if (self.ImaGe == nil)
    {
        return;
    }
    else{
    EMChatImage *imgChat = [[EMChatImage alloc] initWithUIImage:image displayName:@"displayName"];
        
    EMImageMessageBody *body = [[EMImageMessageBody alloc] initWithChatObject:imgChat];
    
//     生成message
    EMMessage *message = [[EMMessage alloc] initWithReceiver:self.conversation.chatter bodies:@[body]];
        message.messageType = eConversationTypeGroupChat;
        
        [[EaseMob sharedInstance].chatManager asyncSendMessage:message progress:nil prepare:^(EMMessage *message, EMError *error)
         {
             
             NSDictionary * dic = @{@"cellType":@"MyImageCell",@"msg":self.ImaGe};
             [self.message_arr addObject:dic];
             [self.tableView reloadData];
             [self setTableViewScoll];
         } onQueue:nil completion:nil onQueue:nil];
   
    
    [self dismissViewControllerAnimated:YES completion:nil];
    }
}

-(void)seedPhoto
{
    
    UIActionSheet *actionsheet = [[UIActionSheet alloc]initWithTitle:@"提示" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"拍照",@"从相册选择",nil];
     actionsheet.delegate = self;
    [actionsheet showInView:self.view];
}

//-(void)ChoicePhoto
//{
//    UIActionSheet *a = [[UIActionSheet alloc]initWithTitle:@"照片来自" delegate:self cancelButtonTitle:@"好的" destructiveButtonTitle:nil otherButtonTitles:@"来自相册",@"来自相机", nil];
//    
//    a.delegate = self;
//    [a showInView:self.view];
//}


-(void)voiceCall
{


    UIStoryboard * story = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
    UIViewController * vc = [story instantiateViewControllerWithIdentifier:@"voiceCall"];
    [vc setValue:self.conversation forKey:@"conversation"];
    
    [self presentViewController:vc animated:YES completion:nil];
}

-(void)videoCall
{
    
    UIStoryboard * story = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
    UIViewController * vc = [story instantiateViewControllerWithIdentifier:@"VideoCall"];
    
    [vc setValue:self.conversation forKey:@"conversation"];
    
    [self presentViewController:vc animated:YES completion:nil];
}


#pragma - mark 键盘通知回调
-(void)receiveNoti:(NSNotification *)noti
{
    
    __weak __block ChatViewController * copy_self = self;
    
    NSDictionary * dic = noti.userInfo;
    
    
    //键盘弹起后的frame
    NSValue * endV = dic[UIKeyboardFrameEndUserInfoKey];
    
    CGRect endFrame = [endV CGRectValue];
    
    NSNumber * d = dic[UIKeyboardAnimationDurationUserInfoKey];
    NSNumber * c = dic[UIKeyboardAnimationCurveUserInfoKey];
    
    [UIView animateWithDuration:[d floatValue] animations:^{
        [UIView setAnimationCurve:[c intValue]];
        CGRect frame = copy_self.view.frame;
        frame.size.height = endFrame.origin.y;
        copy_self.view.frame = frame;
        [copy_self.view layoutIfNeeded];
        
        
        [self.tableView reloadData];
        [self setTableViewScoll];

    }];
}
#pragma - mark TableView  DataSourse

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    
    return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    return self.message_arr.count;

}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    

    NSDictionary *dic = self.message_arr[indexPath.row];
    NSString *ID = dic[@"cellType"];
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    if (!cell)
    {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
    }

    
    [cell setCellInfoWithNSDictionary:dic];
   
    
    
    return cell;

}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    NSDictionary *dic = self.message_arr[indexPath.row];
    NSString *ID = dic[@"cellType"];
    if ([ID isEqualToString:@"MyImageCell" ])
    {
        BigImageViewViewController *bigImageVc = [self.storyboard instantiateViewControllerWithIdentifier:@"TopImagecell"];
        bigImageVc.myImageCell = dic[@"msg"];
        [self.navigationController pushViewController:bigImageVc animated:YES];
    }
    [self.view endEditing:YES];
    
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    
    [self.view endEditing:YES];
}


- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
  
    return NO;
}

//设置表示图
-(void)setTableViewScoll
{
    
//    
//    if (self.message_arr.count > 4)
//    {
    
        NSIndexPath * indexPath = [NSIndexPath indexPathForRow:self.message_arr.count-1 inSection:0];
    
        [self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];
    
        [self.tableView reloadData];
//   }

}


- (BOOL)convertAMR:(NSString *)amrFilePath
             toWAV:(NSString *)wavFilePath
{
    BOOL ret = NO;
    BOOL isFileExists = [[NSFileManager defaultManager] fileExistsAtPath:amrFilePath];
    if (isFileExists)
    {
        [EMVoiceConverter amrToWav:amrFilePath wavSavePath:wavFilePath];
        isFileExists = [[NSFileManager defaultManager] fileExistsAtPath:wavFilePath];
        if (isFileExists)
        {
            ret = YES;
        }
    }
    
    return ret;
}

- (BOOL)convertWAV:(NSString *)wavFilePath
             toAMR:(NSString *)amrFilePath
{
    BOOL ret = NO;
    BOOL isFileExists = [[NSFileManager defaultManager] fileExistsAtPath:wavFilePath];
    if (isFileExists) {
        [EMVoiceConverter wavToAmr:wavFilePath amrSavePath:amrFilePath];
        isFileExists = [[NSFileManager defaultManager] fileExistsAtPath:amrFilePath];
        if (!isFileExists) {
            
        } else {
            ret = YES;
        }
    }
    
    return ret;
}

+(UIImage *)getImage:(NSString *)videoURL
{
    
    AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:[NSURL fileURLWithPath:videoURL] options:nil];
    
    AVAssetImageGenerator *gen = [[AVAssetImageGenerator alloc] initWithAsset:asset];
    
    gen.appliesPreferredTrackTransform = YES;
    
    CMTime time = CMTimeMakeWithSeconds(0.0, 600);
    
    NSError *error = nil;
    
    CMTime actualTime;
    
    CGImageRef image = [gen copyCGImageAtTime:time actualTime:&actualTime error:&error];
    
    UIImage *thumb = [[UIImage alloc] initWithCGImage:image];
    
    CGImageRelease(image);
    
    return thumb;
    
}

- (NSURL *)convert2Mp4:(NSURL *)movUrl
{
    NSURL *mp4Url = nil;
    AVURLAsset *avAsset = [AVURLAsset URLAssetWithURL:movUrl options:nil];
    NSArray *compatiblePresets = [AVAssetExportSession exportPresetsCompatibleWithAsset:avAsset];
    
    if ([compatiblePresets containsObject:AVAssetExportPresetHighestQuality]) {
        AVAssetExportSession *exportSession = [[AVAssetExportSession alloc]initWithAsset:avAsset
                                                                              presetName:AVAssetExportPresetHighestQuality];
        mp4Url = [movUrl copy];
        mp4Url = [mp4Url URLByDeletingPathExtension];
        mp4Url = [mp4Url URLByAppendingPathExtension:@"mp4"];
        exportSession.outputURL = mp4Url;
        exportSession.shouldOptimizeForNetworkUse = YES;
        exportSession.outputFileType = AVFileTypeMPEG4;
        dispatch_semaphore_t wait = dispatch_semaphore_create(0l);
        [exportSession exportAsynchronouslyWithCompletionHandler:^{
            switch ([exportSession status]) {
                case AVAssetExportSessionStatusFailed: {
                   
                } break;
                case AVAssetExportSessionStatusCancelled: {
                   
                } break;
                case AVAssetExportSessionStatusCompleted: {
                                   } break;
                default: {
                   
                } break;
            }
            dispatch_semaphore_signal(wait);
        }];
        long timeout = dispatch_semaphore_wait(wait, DISPATCH_TIME_FOREVER);
        if (timeout) {
           
        }
        if (wait) {
            //dispatch_release(wait);
            wait = nil;
        }
    }
    
    return mp4Url;
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/


- (void)keyboardWillShow:(NSNotification *)notification
{
    
    NSDictionary *info = [notification userInfo];
    
//    kbsize.width为键盘宽度，kbsize.height为键盘高度
     CGSize kbSize = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;
    
    [self.tableView setFrame:CGRectMake(0, 0, 320, 528-kbSize.height)];
//        NSString *hStr  = [NSString stringWithFormat:@"H:|-0-[self.tableView]-%f-|",kbSize.height];
//        //创建一个垂直方法约束字符串
//        NSString *vStr  = [NSString stringWithFormat:@"V:|-0-[self.tableview]-0-|"];
//        //views是一个字典
//        //字典包含约束中所有的控件名和控件对象对应的字典
//        //该字典是一个该约束相关的控件的名字典如@{@"button1":button1}
//        //NSDictionaryOfVariableBindings(button1)作用是产生一个字典@{@"button1":button1},二者等价
//        //创建垂直方向约束,返回一个数组,数组中只有一个约束
//        NSArray *vCons = [NSLayoutConstraint constraintsWithVisualFormat:vStr options:0 metrics:0 views:NSDictionaryOfVariableBindings(self.tableView)];
//        //创建水平方向约束
//        NSArray *hCons = [NSLayoutConstraint constraintsWithVisualFormat:hStr options:0 metrics:0 views:NSDictionaryOfVariableBindings(self.tableView)];
//    
//        //最后一步,添加约束到父视图上
//        [self.view addConstraints:vCons];
//        [self.view addConstraints:hCons];
    
//    自适应代码  ,即需要移动视图的高度代码
    
    NSIndexPath * indexPath = [NSIndexPath indexPathForRow:self.message_arr.count-1 inSection:0];
    
    [self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];
}



-(void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"username" object:nil];
}


@end
